package Utils
{
	import flash.display.DisplayObject;
	
	import mx.events.EffectEvent;
	
	import spark.effects.Animate;
	import spark.effects.Fade;

	public class FadeManager
	{
		static private var _instance:FadeManager = null;
		
		private var _animFadeOut:Fade = new Fade();
		private var _animFadeIn:Fade = new Fade();
		
		private var _fadeOut:Object;
		private var _fadeIn:Object;
		
		private var _callBack:Function;
		
		public function FadeManager()
		{
//			<s:Animate id="fadeOutAnimation"
//			effectEnd="fadeOutAnimation_effectEndHandler(event)">
//				<s:SimpleMotionPath property="alpha"
//									valueFrom="1" valueTo="0"/>
//			</s:Animate>
//			<s:Animate id="fadeInAnimation">
//				<s:SimpleMotionPath property="alpha"
//									valueFrom="0" valueTo="1"/>
//			</s:Animate>
			
			_animFadeOut.duration = 200;
			_animFadeOut.alphaTo = 0;
			_animFadeOut.addEventListener(EffectEvent.EFFECT_END, effectEndHandler_fadeOut);
			
			_animFadeIn.duration = 100;
			_animFadeIn.alphaTo = 1;
			_animFadeIn.addEventListener(EffectEvent.EFFECT_END, effectEndHandler_fadeIn);
		}
		
		
		private function effectEndHandler_fadeOut(e:EffectEvent):void
		{
			var obj:DisplayObject;
			
			if (_fadeOut is Array)
			{
				for each (obj in (_fadeOut as Array))
					obj.visible = false;
			}
			else
				(_fadeOut as DisplayObject).visible = false;
			
			if (_fadeIn is Array)
			{
				for each (obj in (_fadeIn as Array))
					obj.visible = true;
			}
			else
				(_fadeIn as DisplayObject).visible = true;
			
			_animFadeIn.play();
		}
		
		
		private function effectEndHandler_fadeIn(e:EffectEvent):void
		{
			if (_callBack != null)
				_callBack();
		}
		
		
		/**
		 * Makes disappear one element and afterward makes appear the other.
		 * @param fadeOut Array or Object
		 * @param fadeIn Array or Object
		 * @param callBack function called at the effect end (optionnal)
		 */
		public function fade(fadeOut:Object, fadeIn:Object, callBack:Function = null):void
		{
			_fadeOut = fadeOut;
			_fadeIn = fadeIn;
			_callBack = callBack;
			
			if (fadeOut is Array)
				_animFadeOut.targets = fadeOut as Array;
			else
				_animFadeOut.target = fadeOut;

			if (fadeIn is Array)
			{
				for each (var obj:DisplayObject in Array(fadeIn))
				{
					obj.visible = false;
					obj.alpha = 0;
				}
				_animFadeIn.targets = fadeIn as Array;
			}
			else
			{
				(fadeIn as DisplayObject).visible = false;
				(fadeIn as DisplayObject).alpha = 0;
				_animFadeIn.target = fadeIn;
			}
			
			_animFadeOut.play();
		}
		
		static public function get instance():FadeManager
		{
			if (!_instance)
			{
				_instance = new FadeManager();
			}
			return _instance;
		}
	}
}